﻿#include "bgapackagemanager.h"
#include <QSettings>
#include <QCoreApplication>
#include <QFileInfo>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include <QDebug>

//#define STRING_FLUFF "fluff"
#define STRING_BYPASS "byPass"
#define STRING_SUB_DAMAGED "subStrateDamaged"
#define STRING_BALL_DAMAGED "ballDamaged"
#define STRING_CAP_DAMAGED "capDamaged"
#define STRING_ONLY_SAVEFAIL "onlySaveFail"
#define STRING_MINI_AREA_RATIO "miniAreaRatio"
#define STRING_MAX_AREA_RATIO "maxAreaRatio"
#define STRING_MINI_CIRCULARITY "miniCircularity"
#define STRING_MINI_SHADOW "miniDamagedRatio"
#define STRING_MINI_SUB_AREA "miniChippingArea"
#define STRING_RESULT_CALI "resultCali"
#define STRING_KEEP_IMAGE "keepImageRatio"
#define STRING_SEPERATE_FOLDER "seperateFolder"
#define STRING_SEPERATE_FOLDER_TEST_COUNT "seperateFolderTestCount"
#define STRING_MINI_CONT_LENGTH "miniDamagedContLength"
#define STRING_MINI_CRESCENT_AREA "miniCrescentArea"
#define STRING_SHOW_NUM_LABEL "showNumLable"
BgaPackageManager::BgaPackageManager()
{
	QString appName = QCoreApplication::applicationName();
	QSettings app(appName, "Config");
	m_type = app.value("Package").toString();
}



void BgaPackageManager::SavePodToFile(POD_INFO p)
{
	QString appName = QCoreApplication::applicationName();
	QSettings app1(appName, "Config");
	//QString package = app.value("Package").toString();
	QString chipType = app1.value("ChipType").toString();
	QString path = QString("%1/Config/package/%3/%2.pod").arg(QCoreApplication::applicationDirPath()).arg(m_type).arg(chipType);
	QFile file(path);
	if (!file.open(QFile::WriteOnly | QFile::Text)) {
		qDebug() << "Error: Cannot write file: " << qPrintable(file.errorString());
		return;
	}
	QXmlStreamWriter xmlWriter(&file);
	xmlWriter.setAutoFormatting(true);
	xmlWriter.writeStartDocument();

	xmlWriter.writeStartElement("property");

	xmlWriter.writeAttribute("rowBallCenter", QString("%1").arg(p.ballsCenter.x()));
	xmlWriter.writeAttribute("columnBallCenter", QString("%1").arg(p.ballsCenter.y()));
	xmlWriter.writeAttribute("ballsPhi", QString("%1").arg(p.ballsPhi));
	xmlWriter.writeAttribute("rowCapCenter", QString("%1").arg(p.capsCenter.x()));
	xmlWriter.writeAttribute("columnCapCenter", QString("%1").arg(p.capsCenter.y()));
	xmlWriter.writeAttribute("capArea", QString("%1").arg(p.meanCapArea));

	foreach(QPointF point, p.ballsPosList) {
		xmlWriter.writeStartElement("ballPos");
		xmlWriter.writeAttribute("row", QString("%1").arg(point.x()));
		xmlWriter.writeAttribute("column", QString("%1").arg(point.y()));
		xmlWriter.writeEndElement();
	}


	foreach(QPointF point, p.capsPosList) {
		xmlWriter.writeStartElement("capPos");
		xmlWriter.writeAttribute("row", QString("%1").arg(point.x()));
		xmlWriter.writeAttribute("column", QString("%1").arg(point.y()));
		xmlWriter.writeEndElement();
	}

	xmlWriter.writeEndElement();

	xmlWriter.writeEndDocument();
	file.close();
	if (file.error()) {
		qDebug() << "Error: Cannot write file: "
			<< qPrintable(file.errorString());
		return;
	}
}

BgaPackageManager::POD_INFO BgaPackageManager::GetPodFromFile()
{
	QString appName = QCoreApplication::applicationName();
	QSettings app1(appName, "Config");
	//QString package = app.value("Package").toString();
	QString chipType = app1.value("ChipType").toString();
	POD_INFO def;
	def.ballsPhi = 0;
	QString path = QString("%1/Config/package/%3/%2.pod").arg(QCoreApplication::applicationDirPath()).arg(m_type).arg(chipType);
	QFile file(path);
	
	if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
		QXmlStreamReader reader(&file);

		while (!reader.atEnd()) {

			QXmlStreamReader::TokenType nType = reader.readNext();

			switch (nType) {
			case QXmlStreamReader::StartElement: {
				QString strElementName = reader.name().toString();
				//  qDebug()<<strElementName;

				if (strElementName.compare("property", Qt::CaseInsensitive) == 0) {
					QXmlStreamAttributes attributes = reader.attributes();
	
					if (attributes.hasAttribute("capArea")) {
						def.meanCapArea = attributes.value("capArea").toDouble();
					}
					if (attributes.hasAttribute("rowBallCenter")) {
						def.ballsCenter.setX(attributes.value("rowBallCenter").toDouble());
					}
					if (attributes.hasAttribute("columnBallCenter")) {
						def.ballsCenter.setY(attributes.value("columnBallCenter").toDouble());
					}
					if (attributes.hasAttribute("ballsPhi")) {
						def.ballsPhi = attributes.value("ballsPhi").toDouble();
					}
					
					if (attributes.hasAttribute("rowCapCenter")) {
						def.capsCenter.setX(attributes.value("rowCapCenter").toDouble());
					}
					if (attributes.hasAttribute("columnCapCenter")) {
						def.capsCenter.setY(attributes.value("columnCapCenter").toDouble());
					}
					
				}
				else if (QString::compare(strElementName, "ballPos") == 0) {  // 根元素
				//    qDebug() << QString("********** 开始元素<emptyPin> ********** ");
					QXmlStreamAttributes attributes = reader.attributes();
					QPointF point;
					if (attributes.hasAttribute("row")) {
						point.setX(attributes.value("row").toDouble());
					}
					if (attributes.hasAttribute("column")) {
						point.setY(attributes.value("column").toDouble());
					}

					def.ballsPosList.append(point);
				}
				else if (QString::compare(strElementName, "capPos") == 0) {  // 根元素
				//    qDebug() << QString("********** 开始元素<emptyPin> ********** ");
					QXmlStreamAttributes attributes = reader.attributes();
					QPointF point;
					if (attributes.hasAttribute("row")) {
						point.setX(attributes.value("row").toDouble());
					}
					if (attributes.hasAttribute("column")) {
						point.setY(attributes.value("column").toDouble());
					}

					def.capsPosList.append(point);
				}
				break;
			}

			default:
				break;
			}
		}

		if (reader.hasError()) {
			qDebug() << QString("err:%1  line:%2  column:%3  pos:%4").arg(reader.errorString()).arg(reader.lineNumber()).arg(reader.columnNumber()).arg(reader.characterOffset());
		}

		file.close();
	}


	return def;
}


void BgaPackageManager::SaveParamToFile(BgaPackageManager::INSPECT_PARAM param)
{
	QString appName = QCoreApplication::applicationName();
	QSettings app1(appName, "Config");
	QString chipType = app1.value("ChipType").toString();
	QString path = QString("%1/Config/package/%3/%2.param").arg(QCoreApplication::applicationDirPath()).arg(m_type).arg(chipType);
	QFile file(path);
	if (!file.open(QFile::WriteOnly | QFile::Text)) {
		qDebug() << "Error: Cannot write file: " << qPrintable(file.errorString());
		return;
	}
	{
		QString appName = QCoreApplication::applicationName();
		QSettings app(appName, "Config");
		app.setValue("AutoRemoveDays", param.saveDays);
	}
	QXmlStreamWriter xmlWriter(&file);
	xmlWriter.setAutoFormatting(true);
	xmlWriter.writeStartDocument();

	xmlWriter.writeStartElement("property");

	//xmlWriter.writeAttribute(STRING_BYPASS, QString("%1").arg(param.bBypass));
	xmlWriter.writeAttribute(STRING_ONLY_SAVEFAIL, QString("%1").arg(param.bOnlySaveFail));
	xmlWriter.writeAttribute(STRING_BALL_DAMAGED, QString("%1").arg(param.bBallDamaged));
	xmlWriter.writeAttribute(STRING_CAP_DAMAGED, QString("%1").arg(param.bCapDamaged));
	xmlWriter.writeAttribute(STRING_SUB_DAMAGED, QString("%1").arg(param.bChipping));
	xmlWriter.writeAttribute(STRING_SHOW_NUM_LABEL, QString("%1").arg(param.bShowNumLabel));
	xmlWriter.writeAttribute(STRING_MINI_CIRCULARITY, QString("%1").arg(param.miniCircularity));
	xmlWriter.writeAttribute(STRING_MINI_AREA_RATIO, QString("%1").arg(param.miniAreaRatio));
	xmlWriter.writeAttribute(STRING_MINI_SUB_AREA, QString("%1").arg(param.miniChippingArea));
	xmlWriter.writeAttribute(STRING_MINI_SHADOW, QString("%1").arg(param.miniDamagedRatio));
	xmlWriter.writeAttribute(STRING_MAX_AREA_RATIO, QString("%1").arg(param.maxAreaRatio));
	xmlWriter.writeAttribute(STRING_RESULT_CALI, QString("%1").arg(param.bResultCali));
	xmlWriter.writeAttribute(STRING_KEEP_IMAGE, QString("%1").arg(param.bKeepImageRatio));
	xmlWriter.writeAttribute(STRING_SEPERATE_FOLDER, QString("%1").arg(param.bSeperateFolder));
	xmlWriter.writeAttribute(STRING_SEPERATE_FOLDER_TEST_COUNT, QString("%1").arg(param.iCountForSeperateFolder));
	xmlWriter.writeAttribute(STRING_MINI_CONT_LENGTH, QString("%1").arg(param.miniDamagedContLength));
	xmlWriter.writeAttribute(STRING_MINI_CRESCENT_AREA, QString("%1").arg(param.miniCrescentArea));
	xmlWriter.writeEndElement();

	xmlWriter.writeEndDocument();
	file.close();
	if (file.error()) {
		qDebug() << "Error: Cannot write file: "
			<< qPrintable(file.errorString());
		return;
	}
}

BgaPackageManager::INSPECT_PARAM BgaPackageManager::GetParamFromFile()
{
	INSPECT_PARAM param;
	param.bBallDamaged = param.bChipping = param.bCapDamaged  = true;
	QString appName = QCoreApplication::applicationName();
	QSettings app(appName, "Debug");

	param.bBypass = app.value("bypass").toInt();
	param.bShowNumLabel = false;
	param.bResultCali = true;
	param.miniDamagedRatio = 30;
	param.miniChippingArea = 235;
	param.miniAreaRatio = 70;
	param.maxAreaRatio = 130;
	param.miniCircularity = 66;
	param.bOnlySaveFail = false;
	param.bKeepImageRatio = false;
	param.bSeperateFolder = false;
	param.iCountForSeperateFolder = 100;
	param.miniDamagedContLength = 30;
	param.miniCrescentArea = 10;
	param.saveDays = 15;
	//QString appName = QCoreApplication::applicationName();
	QSettings app1(appName, "Config");
	//QString package = app.value("Package").toString();
	QString chipType = app1.value("ChipType").toString();
	QString path = QString("%1/Config/package/%3/%2.param").arg(QCoreApplication::applicationDirPath()).arg(m_type).arg(chipType);
	QFile file(path);

	if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
		QXmlStreamReader reader(&file);

		while (!reader.atEnd()) {

			QXmlStreamReader::TokenType nType = reader.readNext();

			switch (nType) {
			case QXmlStreamReader::StartElement: {
				QString strElementName = reader.name().toString();
				//  qDebug()<<strElementName;

				if (strElementName.compare("property", Qt::CaseInsensitive) == 0) {
					QXmlStreamAttributes attributes = reader.attributes();

					/*if (attributes.hasAttribute(STRING_BYPASS)) {
						param.bBypass = attributes.value(STRING_BYPASS).toInt();
					}*/
					if (attributes.hasAttribute(STRING_BYPASS)) {
						param.bShowNumLabel = attributes.value(STRING_SHOW_NUM_LABEL).toInt();
					}
					if (attributes.hasAttribute(STRING_ONLY_SAVEFAIL)) {
						param.bOnlySaveFail = attributes.value(STRING_ONLY_SAVEFAIL).toInt();
					}
					if (attributes.hasAttribute(STRING_CAP_DAMAGED)) {
						param.bCapDamaged = attributes.value(STRING_CAP_DAMAGED).toInt();
					}
					if (attributes.hasAttribute(STRING_SUB_DAMAGED)) {
						param.bChipping = attributes.value(STRING_SUB_DAMAGED).toInt();
					}
					if (attributes.hasAttribute(STRING_BALL_DAMAGED)) {
						param.bBallDamaged = attributes.value(STRING_BALL_DAMAGED).toInt();
					}
					if (attributes.hasAttribute(STRING_RESULT_CALI)) {
						param.bResultCali = attributes.value(STRING_RESULT_CALI).toInt();
					}
					if (attributes.hasAttribute(STRING_KEEP_IMAGE)) {
						param.bKeepImageRatio = attributes.value(STRING_KEEP_IMAGE).toInt();
					}
					if (attributes.hasAttribute(STRING_SEPERATE_FOLDER)) {
						param.bSeperateFolder = attributes.value(STRING_SEPERATE_FOLDER).toInt();
					}
					if (attributes.hasAttribute(STRING_SEPERATE_FOLDER_TEST_COUNT)) {
						param.iCountForSeperateFolder = attributes.value(STRING_SEPERATE_FOLDER_TEST_COUNT).toInt();
					}
					
					if (attributes.hasAttribute(STRING_MINI_AREA_RATIO)) {
						param.miniAreaRatio = attributes.value(STRING_MINI_AREA_RATIO).toInt();
					}
					if (attributes.hasAttribute(STRING_MINI_SUB_AREA)) {
						param.miniChippingArea = attributes.value(STRING_MINI_SUB_AREA).toInt();
					}
					if (attributes.hasAttribute(STRING_MINI_CIRCULARITY)) {
						param.miniCircularity = attributes.value(STRING_MINI_CIRCULARITY).toInt();
					}
					if (attributes.hasAttribute(STRING_MINI_SHADOW)) {
						param.miniDamagedRatio = attributes.value(STRING_MINI_SHADOW).toInt();
					}
					if (attributes.hasAttribute(STRING_MAX_AREA_RATIO)) {
						param.maxAreaRatio = attributes.value(STRING_MAX_AREA_RATIO).toInt();
					}
					if (attributes.hasAttribute(STRING_MINI_CONT_LENGTH)) {
						param.miniDamagedContLength = attributes.value(STRING_MINI_CONT_LENGTH).toInt();
					}
					if (attributes.hasAttribute(STRING_MINI_CRESCENT_AREA)) {
						param.miniCrescentArea = attributes.value(STRING_MINI_CRESCENT_AREA).toInt();
					}
				}
				
				break;
			}

			default:
				break;
			}
		}

		if (reader.hasError()) {
			qDebug() << QString("err:%1  line:%2  column:%3  pos:%4").arg(reader.errorString()).arg(reader.lineNumber()).arg(reader.columnNumber()).arg(reader.characterOffset());
		}

		file.close();
	}
	{
		QString appName = QCoreApplication::applicationName();
		QSettings app(appName, "Config");
		int days = app.value("AutoRemoveDays").toString().toInt();
		if (days > 0)
		{
			param.saveDays = days;
		}
	}
	
	return param;
}

